﻿using Mes.Domain.BoundedContext;

namespace Mes.Infrastructure.Data.BoundedContext.Extensions
{
    public static class QueryableExtensions
    {
        public static Task<Paged<TEntity>> ToPagedAsync<TEntity>(this IQueryable<TEntity> source, int page, int itemsPerPage, long? totalCount = null,
                                                                CancellationToken cancellationToken = default(CancellationToken))
        {
            if (page < 1)
                throw new ArgumentOutOfRangeException(nameof(page));
            if (itemsPerPage < 1)
                throw new ArgumentOutOfRangeException(nameof(itemsPerPage));

            return Task.Run(() =>
            {
                if (!totalCount.HasValue || totalCount.Value < 0)
                    totalCount = source.Count();
                var items = source.Skip((page - 1) * itemsPerPage).Take(itemsPerPage).ToList();

                return new Paged<TEntity>
                {
                    CurrentPage = page,
                    ItemsPerPage = itemsPerPage,
                    TotalItems = totalCount.Value,
                    TotalPages = (int)Math.Ceiling((double)totalCount / itemsPerPage),
                    Items = items
                };
            }, cancellationToken);
        }

        public static Task<Paged<TEntity>> ToPagedAsync<TEntity>(this IQueryable<TEntity> source, PagedInput paged, CancellationToken cancellationToken = default(CancellationToken))
        {
            return source.ToPagedAsync(paged.PageNo, paged.PageSize, paged.TotalItems, cancellationToken);
        }
    }
}
